<!-- src/components/FilesUpload.vue -->
 <!-- 用于多文件传入 -->
<template>
    <div>
      <el-upload
        class="upload-demo"
        drag
        action=""
        :multiple="true"
        :before-upload="handleBeforeUpload"
        :directory="true"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        fileData: []
      };
    },
    methods: {
      async handleBeforeUpload(file) {
        if (file.type === 'text/plain') {
          await this.processFile(file);
        } else if (file.webkitRelativePath) {
          const files = await this.getFilesFromDirectory(file);
          for (const txtFile of files) {
            await this.processFile(txtFile);
          }
        }
        return false; // 阻止文件自动上传
      },
      async processFile(file) {
        const reader = new FileReader();
        reader.onload = (event) => {
          const content = event.target.result;
          this.extractData(content, file.name);
        };
        reader.readAsText(file);
      },
      async getFilesFromDirectory(directory) {
        const entries = directory.items || [];
        const txtFiles = [];
  
        for (const entry of entries) {
          if (entry.isFile && entry.name.endsWith('.txt')) {
            const file = await this.readFileEntry(entry);
            txtFiles.push(file);
          }
        }
        return txtFiles;
      },
      readFileEntry(entry) {
        return new Promise((resolve, reject) => {
          entry.file((file) => {
            resolve(file);
          }, reject);
        });
      },
      extractData(content, fileName) {
        const lines = content.split('\n');
        const dataLines = lines.filter(line => this.isDataLine(line));
  
        const wavelengths = [];
        const intensities = [];
  
        dataLines.forEach(line => {
          const [wavelength, intensity] = line.split(',').map(Number);
          if (!isNaN(wavelength) && !isNaN(intensity)) {
            wavelengths.push(wavelength);
            intensities.push(intensity);
          }
        });
  
        this.fileData.push({
          fileName: fileName,
          wavelengths: wavelengths,
          intensities: intensities
        });
  
        // 将所有文件数据传递给父组件
        this.$emit('data-extracted', this.fileData);
      },
      isDataLine(line) {
        // 正则表达式匹配数值数据行
        const regex = /^-?\d+(\.\d+)?,-?\d+(\.\d+)?$/;
        return regex.test(line.trim());
      }
    }
  };
  </script>
  
  <style scoped>
  .upload-demo {
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    background-color: #fafafa;
    text-align: center;
    padding: 20px;
    cursor: pointer;
  }
  </style>
  